import threading
from scapy.all import *
import json

from scapy.layers.dns import DNS
from scapy.layers.inet import IP, ICMP, TCP, in4_chksum, UDP
from scapy.layers.inet6 import IPv6
from scapy.layers.l2 import Ether, ARP


def string_to_int(s):
    if s == "":
        # 返回无限大
        return -1
    try :
        return int(s)
    except ValueError:
        return 0

class Analysis:
    def __init__(self,count,condition):
        self.sniffFlag = True # 标志变量
        #如果count字符串中有除了字符之外的符号，无法转换为数字，直接为零
        self.count = string_to_int(count)
        self.condition = condition.upper()
        self.countAct = 0 # 记录捕获了多少的数据帧
        self.sniffDataList = [] #用于保存捕获的数据
        self.listbox = [] # 用于动态获取报文
        self.current_packet = []
        self.hexadecimal_dump = []

    def start_sniff(self):
        print("开始新的报文捕获！")
        print(f"condition:{self.condition}\ncount:{self.count}\ncountAct:{self.countAct}\n\n\n")
        self.sniffFlag = False
        t = threading.Thread(target=self.PDU_sniff, name='LoopThread')
        t.start()
        print(threading.current_thread().name + ' 1')

    def refresh(self, count, condition):
        # 确保之前的捕获已经停止
        if not self.sniffFlag:
            self.stop_sniff()
        self.count = string_to_int(count)
        self.condition = condition.upper()
        self.countAct = 0

    def PDU_sniff(self):
        # 根据count值决定捕获数量
        sniff_count = 0 if self.count == -1 else self.count
        sniff(filter="arp or ip or ip6 or tcp or udp",
              prn=(lambda x: self.ip_monitor_callback(x)),
              stop_filter=(lambda x: self.sniffFlag),
              store=0)

    def stop_sniff(self):
        print(f"condition:{self.condition}\ncount:{self.count}\ncountAct:{self.countAct}\n\n\n")
        self.sniffFlag = True
        self.count = 0
        self.countAct = 0

    def clear_data(self):
        """
        清理捕获的数据，将 sniffDataList 和 listbox 清空
        """
        self.sniffDataList.clear()
        self.listbox.clear()
        self.countAct = 0
        print("数据已清理")

    # 分割条件的函数
    def split_condition(self):
        conditionString = self.condition
        splitList = conditionString.split(' ')
        splitStrings = []
        for conString in splitList:
            splitStrings.append(conString)
        return splitStrings

    def split_dulequal(self, dul):  # 按照等号划分后获得筛选的条件
        splitList = dul.split('==')
        return splitList[1]

    #回调函数，根据筛选条件调用不同的分析函数
    def ip_monitor_callback(self, pkt):
        print("=== 新数据包 ===")
        pkt.show()  # 显示完整数据包结构
        pktSummaryInfo = str(self.countAct) + ' ' + pkt.summary()
        if self.condition.find('IP') != -1:
            src_IP = ''
            dst_IP = ''
            proto_IP = ''
            if pkt.haslayer('IP') and (self.count == -1 or self.countAct < self.count):
                split_condition = self.split_condition()
                for split_con in split_condition:
                    if split_con.find('src') != -1:
                        src_IP = self.split_dulequal(split_con)
                    if split_con.find('dst') != -1:
                        dst_IP = self.split_dulequal(split_con)
                    if split_con.find('proto') != -1:
                        proto_IP = int(self.split_dulequal(split_con))
                if src_IP != '' and dst_IP != '' and proto_IP != '':
                    if pkt['IP'].src == src_IP and pkt['IP'].dst == dst_IP and pkt['IP'].proto == proto_IP:
                        self.sniffDataList.append(pkt)  # 把sniff函数抓到的数据包加入到捕获队列里
                        self.listbox.append(pktSummaryInfo)
                        self.countAct+=1
                if src_IP != '' and dst_IP != '' and proto_IP == '':
                    if pkt['IP'].src == src_IP and pkt['IP'].dst == dst_IP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if src_IP != '' and dst_IP == '' and proto_IP != '':
                    if pkt['IP'].src == src_IP and pkt['IP'].proto == proto_IP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if src_IP == '' and dst_IP != '' and proto_IP != '':
                    if pkt['IP'].dst == dst_IP and pkt['IP'].proto == proto_IP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if src_IP != '' and dst_IP == '' and proto_IP == '':
                    if pkt['IP'].src == src_IP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if src_IP == '' and dst_IP == '' and proto_IP != '':
                    if pkt['IP'].proto == proto_IP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if src_IP == '' and dst_IP != '' and proto_IP == '':
                    if pkt['IP'].dst == dst_IP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if src_IP == '' and dst_IP == '' and proto_IP == '':
                    self.sniffDataList.append(pkt)
                    self.listbox.append(pktSummaryInfo)
                    self.countAct += 1
            if self.count != -1 and self.countAct == self.count:
                self.stop_sniff()

        elif self.condition.find('ARP') != -1:
            hwsrc_ARP = ''
            hwdst_ARP = ''
            psrc_ARP = ''
            pdst_ARP = ''
            op_ARP = ''
            if pkt.haslayer('ARP') and (self.count == -1 or self.countAct < self.count):
                split_condition = self.split_condition()
                for split_con in split_condition:
                    if split_con.find('hwsrc') != -1:
                        hwsrc_ARP = self.split_dulequal(split_con)
                    if split_con.find('hwdst') != -1:
                        hwdst_ARP = self.split_dulequal(split_con)
                    if split_con.find('psrc') != -1:
                        psrc_ARP = self.split_dulequal(split_con)
                    if split_con.find('pdst') != -1:
                        pdst_ARP = self.split_dulequal(split_con)
                    if split_con.find('op') != -1:
                        op_ARP = self.split_dulequal(split_con)
                if op_ARP != '' and hwsrc_ARP != '' and hwdst_ARP != '' and psrc_ARP != '' and pdst_ARP != '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].hwdst == hwdst_ARP and pkt[
                        'ARP'].psrc == psrc_ARP and pkt['ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)  # 把sniff函数抓到的数据包加入到捕获队列里
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP != '' and hwdst_ARP != '' and psrc_ARP != '' and pdst_ARP == '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].hwdst == hwdst_ARP and pkt[
                        'ARP'].psrc == psrc_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP != '' and hwdst_ARP != '' and psrc_ARP == '' and pdst_ARP != '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].hwdst == hwdst_ARP and pkt[
                        'ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP != '' and hwdst_ARP == '' and psrc_ARP != '' and pdst_ARP != '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].psrc == psrc_ARP and pkt[
                        'ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP == '' and hwdst_ARP != '' and psrc_ARP != '' and pdst_ARP != '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].hwdst == hwdst_ARP and pkt['ARP'].psrc == psrc_ARP and pkt[
                        'ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP != '' and hwdst_ARP != '' and psrc_ARP != '' and pdst_ARP != '':
                    if pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].hwdst == hwdst_ARP and pkt['ARP'].psrc == psrc_ARP and \
                            pkt['ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP != '' and hwdst_ARP != '' and psrc_ARP == '' and pdst_ARP == '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].hwdst == hwdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP != '' and hwdst_ARP == '' and psrc_ARP != '' and pdst_ARP == '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].psrc == psrc_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP == '' and hwdst_ARP != '' and psrc_ARP != '' and pdst_ARP == '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].hwdst == hwdst_ARP and pkt['ARP'].psrc == psrc_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP != '' and hwdst_ARP != '' and psrc_ARP != '' and pdst_ARP == '':
                    if pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].hwdst == hwdst_ARP and pkt['ARP'].psrc == psrc_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP != '' and hwdst_ARP == '' and psrc_ARP == '' and pdst_ARP != '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP == '' and hwdst_ARP != '' and psrc_ARP == '' and pdst_ARP != '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].hwdst == hwdst_ARP and pkt['ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP != '' and hwdst_ARP != '' and psrc_ARP == '' and pdst_ARP != '':
                    if pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].hwdst == hwdst_ARP and pkt['ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP == '' and hwdst_ARP == '' and psrc_ARP != '' and pdst_ARP != '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].psrc == psrc_ARP and pkt['ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP != '' and hwdst_ARP == '' and psrc_ARP != '' and pdst_ARP != '':
                    if pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].psrc == psrc_ARP and pkt['ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP == '' and hwdst_ARP != '' and psrc_ARP != '' and pdst_ARP != '':
                    if pkt['ARP'].hwdst == hwdst_ARP and pkt['ARP'].psrc == psrc_ARP and pkt['ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP != '' and hwdst_ARP == '' and psrc_ARP == '' and pdst_ARP == '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].hwsrc == hwsrc_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP == '' and hwdst_ARP != '' and psrc_ARP == '' and pdst_ARP == '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].hwdst == hwdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP != '' and hwdst_ARP != '' and psrc_ARP == '' and pdst_ARP == '':
                    if pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].hwdst == hwdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP == '' and hwdst_ARP == '' and psrc_ARP != '' and pdst_ARP == '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].psrc == psrc_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP != '' and hwdst_ARP == '' and psrc_ARP != '' and pdst_ARP == '':
                    if pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].psrc == psrc_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP == '' and hwdst_ARP != '' and psrc_ARP != '' and pdst_ARP == '':
                    if pkt['ARP'].hwdst == hwdst_ARP and pkt['ARP'].psrc == psrc_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP == '' and hwdst_ARP == '' and psrc_ARP == '' and pdst_ARP != '':
                    if pkt['ARP'].op == op_ARP and pkt['ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP != '' and hwdst_ARP == '' and psrc_ARP == '' and pdst_ARP != '':
                    if pkt['ARP'].hwsrc == hwsrc_ARP and pkt['ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP == '' and hwdst_ARP != '' and psrc_ARP == '' and pdst_ARP != '':
                    if pkt['ARP'].hwdst == hwdst_ARP and pkt['ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP == '' and hwdst_ARP == '' and psrc_ARP != '' and pdst_ARP != '':
                    if pkt['ARP'].psrc == psrc_ARP and pkt['ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP == '' and hwdst_ARP == '' and psrc_ARP == '' and pdst_ARP != '':
                    if pkt['ARP'].pdst == pdst_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP == '' and hwdst_ARP == '' and psrc_ARP != '' and pdst_ARP == '':
                    if pkt['ARP'].psrc == psrc_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP == '' and hwdst_ARP != '' and psrc_ARP == '' and pdst_ARP == '':
                    if pkt['ARP'].hwdst == hwdst_ARP:
                        self.sniffDataList.append(pkt)  # 把sniff函数抓到的数据包加入到捕获队列里
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP != '' and hwdst_ARP == '' and psrc_ARP == '' and pdst_ARP == '':
                    if pkt['ARP'].hwsrc == hwsrc_ARP:
                        self.sniffDataList.append(pkt)  # 把sniff函数抓到的数据包加入到捕获队列里
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP != '' and hwsrc_ARP == '' and hwdst_ARP == '' and psrc_ARP == '' and pdst_ARP == '':
                    if pkt['ARP'].op == op_ARP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if op_ARP == '' and hwsrc_ARP == '' and hwdst_ARP == '' and psrc_ARP == '' and pdst_ARP == '':
                    self.sniffDataList.append(pkt)
                    self.listbox.append(pktSummaryInfo)
                    self.countAct += 1
            if self.count != -1 and self.countAct == self.count:
                self.stop_sniff()

        elif self.condition.find('ETHER') != -1:
            src_Ether = ''
            dst_Ether = ''
            if pkt.haslayer('Ether') and (self.count == -1 or self.countAct < self.count):
                split_condition = self.split_condition()
                for split_con in split_condition:
                    if split_con.find('src') != -1:
                        src_Ether = self.split_dulequal(split_con)
                    if split_con.find('dst') != -1:
                        dst_Ether = self.split_dulequal(split_con)
                if src_Ether != '' and dst_Ether != '':
                    if pkt['Ether'].src == src_Ether and pkt['Ether'].dst == dst_Ether:
                        self.sniffDataList.append(pkt)  # 把sniff函数抓到的数据包加入到捕获队列里
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if src_Ether != '' and dst_Ether == '':
                    if pkt['Ether'].src == src_Ether:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if src_Ether == '' and dst_Ether != '':
                    if pkt['Ether'].dst == dst_Ether:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if src_Ether == '' and dst_Ether == '':
                    self.sniffDataList.append(pkt)
                    self.listbox.append(pktSummaryInfo)
                    self.countAct += 1
            if self.count != -1 and self.countAct == self.count:
                self.stop_sniff()

        elif self.condition.find('TCP') != -1:
            sport_TCP = ''
            dport_TCP = ''
            if pkt.haslayer('TCP') and (self.count == -1 or self.countAct < self.count):
                split_condition = self.split_condition()
                for split_con in split_condition:
                    if split_con.find('sport') != -1:
                        sport_TCP = int(self.split_dulequal(split_con))
                    if split_con.find('dport') != -1:
                        dport_TCP = int(self.split_dulequal(split_con))
                    # # 在比较时使用 None 而不是空字符串
                    # sport_TCP = sport_TCP if 'sport_TCP' in locals() else None
                    # dport_TCP = dport_TCP if 'dport_TCP' in locals() else None
                if sport_TCP != '' and dport_TCP != '':
                    if pkt['TCP'].sport == sport_TCP and pkt['TCP'].dport == dport_TCP:
                        self.sniffDataList.append(pkt)  # 把sniff函数抓到的数据包加入到捕获队列里
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if sport_TCP != '' and dport_TCP == '':
                    if pkt['TCP'].sport == sport_TCP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if sport_TCP == '' and dport_TCP != '':
                    if pkt['TCP'].dport == dport_TCP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if sport_TCP == '' and dport_TCP == '':
                    self.sniffDataList.append(pkt)
                    self.listbox.append(pktSummaryInfo)
                    self.countAct += 1
            if self.count != -1 and self.countAct == self.count:
                    self.stop_sniff()

        elif self.condition.find('UDP') != -1:
            sport_UDP = ''
            dport_UDP = ''
            if pkt.haslayer('UDP') and (self.count == -1 or self.countAct < self.count):
                split_condition = self.split_condition()
                for split_con in split_condition:
                    if split_con.find('sport') != -1:
                        sport_UDP = int(self.split_dulequal(split_con))
                    if split_con.find('dport') != -1:
                        dport_UDP = int(self.split_dulequal(split_con))
                if sport_UDP != '' and dport_UDP != '':
                    if pkt['UDP'].sport == sport_UDP and pkt['UDP'].dport == dport_UDP:
                        self.sniffDataList.append(pkt)  # 把sniff函数抓到的数据包加入到捕获队列里
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if sport_UDP != '' and dport_UDP == '':
                    if pkt['UDP'].sport == sport_UDP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if sport_UDP == '' and dport_UDP != '':
                    if pkt['UDP'].dport == dport_UDP:
                        self.sniffDataList.append(pkt)
                        self.listbox.append(pktSummaryInfo)
                        self.countAct += 1
                if sport_UDP == '' and dport_UDP == '':
                    self.sniffDataList.append(pkt)
                    self.listbox.append(pktSummaryInfo)
                    self.countAct += 1
            if self.count != -1 and self.countAct == self.count:
                    self.stop_sniff()
        else:
            if self.count == -1 or self.count > self.countAct:
                print("=== 未过滤数据包 ===")
                pkt.show()  # 添加这行来显示所有未被过滤的数据包
                self.countAct += 1
                self.sniffDataList.append(pkt)
                self.listbox.append(pktSummaryInfo)

        print(threading.current_thread().name+' 2') # https://blog.csdn.net/briblue/article/details/85101144
        # time.sleep(1) # 最好不要延时，否则好多包抓不到

    def choosedPDUAnalysis(self, idx):
        print(f"\n\n我要查看数据了，数据索引：{idx}\n\n")
        self.current_packet.clear()
        self.hexadecimal_dump.clear()
        self.choosePDUNum = idx
        choosedPacket = self.sniffDataList[self.choosePDUNum]
        print(choosedPacket)
        # choosedPacket.show()
        self.generate_hex_dump(choosedPacket)
        if choosedPacket.haslayer('Ether'):  # 以太网MAC协议
            self.choosedEtherPDUAnalysis()
        if choosedPacket.haslayer('IP'):
            self.choosedIPPDUAnalysis()
        if choosedPacket.haslayer('IPv6'):
            self.choosedIPv6PDUAnalysis()
        if choosedPacket.haslayer('ARP'):
            self.choosedARPPDUAnalysis()
        if choosedPacket.haslayer('TCP'):
            self.choosedTCPPDUAnalysis()
        if choosedPacket.haslayer('UDP'):
            self.choosedUDPPDUAnalysis()
        # if self.condition.find('IP') != -1 :
        #     self.choosedIPPDUAnalysis()
        # elif self.condition.find('ARP') != -1:
        #     self.choosedARPPDUAnalysis()
        # elif self.condition.find('ETHER') != -1: # 以太网MAC协议
        #     self.choosedEtherPDUAnalysis()
        # elif self.condition.find('TCP') != -1:
        #     self.choosedTCPPDUAnalysis()
        # elif self.condition.find('UDP') != -1:
        #     self.choosedUDPPDUAnalysis()
        # elif self.condition == '':
        #     if choosedPacket.haslayer('IP'):
        #         self.choosedIPPDUAnalysis()
        #     elif choosedPacket.haslayer('ARP'):
        #         self.choosedARPPDUAnalysis()
        #     elif choosedPacket.haslayer('Ether'): # 以太网MAC协议
        #         self.choosedEtherPDUAnalysis()
        #     elif choosedPacket.haslayer('TCP'):
        #         self.choosedTCPPDUAnalysis()
        #     elif choosedPacket.haslayer('UDP'):
        #         self.choosedUDPPDUAnalysis()
        # else:
        #     print("\n\n=== 未识别数据包 ===")

    def choosedEtherPDUAnalysis(self):
        net_packet = {}
        choosedPacket = self.sniffDataList[self.choosePDUNum]
        net_packet['net_type'] = f"Ethernet II, Src: {choosedPacket['Ether'].src}, Dst: {choosedPacket['Ether'].dst}"
        net_packet['details'] = [
            f"   Destination: {choosedPacket['Ether'].dst}",
            f"   Source       : {choosedPacket['Ether'].src}",
            f"   Type          : {choosedPacket['Ether'].type}"
        ]
        self.current_packet.append(net_packet)

    def choosedIPPDUAnalysis(self):
        # 请在此处完成IP协议的分析器(分析数据包功能)，并添加详细代码注释
        print("\n\nIP协议\n")
        net_packet = {}
        choosedPacket = self.sniffDataList[self.choosePDUNum]
        choosedPacket.show()
        # 解析Flags字段
        flags_value = int(choosedPacket['IP'].flags) if hasattr(choosedPacket['IP'].flags, '__int__') else \
            choosedPacket['IP'].flags
        flags_binary = format(flags_value, '03b')  # 转换为3位二进制字符串
        # 构造详细的Flags输出
        reserved_bit = flags_binary[0]
        dont_fragment = flags_binary[1]
        more_fragments = flags_binary[2]
        # 构造Flags的详细描述
        flags_description = []
        if dont_fragment == '1':
            flags_description.append("Don't fragment")
        if more_fragments == '1':
            flags_description.append("More fragments")
        # 如果没有设置任何标志，则添加"Reserved"
        if not flags_description:
            flags_description.append("Reserved")

        flags_detail = f"0x{flags_value:04x}, {', '.join(flags_description)} \n"\
                       f"          {reserved_bit} . . .  . . . .  . . . .  . . . . = Reserved bit: {'Not set' if reserved_bit == '0' else 'Set'}\n" \
                       f"          .{dont_fragment} . .  . . . .  . . . .  . . . . = Don't fragment: {'Not set' if dont_fragment == '0' else 'Set'}\n" \
                       f"          . .{more_fragments} .  . . . .  . . . .  . . . . = More fragments: {'Not set' if more_fragments == '0' else 'Set'}"

        original_checksum = choosedPacket['IP'].chksum
        # 使用定义的IP_headchecksum函数计算校验和
        # 首先创建IP头部的副本并将校验和字段设置为0
        ip_header_copy = choosedPacket['IP'].copy()
        ip_header_copy.chksum = 0
        # 将IP头部转换为字节串
        ip_header_bytes = bytes(ip_header_copy)
        # 计算IP头部的校验和
        calculated_checksum = self.IP_headchecksum(ip_header_bytes[:ip_header_copy.ihl * 4])
        # 检查校验和状态
        if original_checksum == calculated_checksum:
            checksum_status = "Good"
        else:
            checksum_status = "Bad"

        # 根据校验和状态决定显示的标记
        checksum_marker = "[correct]" if checksum_status == "Good" else "[incorrect]" if checksum_status == "Bad" else "[unverified]"

        # 构造Header Checksum的详细输出
        checksum_detail = f"0x{original_checksum:04x} {checksum_marker}\n" \
                          f"      [Header checksum status: {checksum_status}]\n" \
                          f"      [Calculated Checksum: 0x{calculated_checksum:04x}]"


        net_packet["net_type"] = f"Internet Protocol Version 4, Src: {choosedPacket['IP'].src}, Dst: {choosedPacket['IP'].dst}"
        net_packet["details"] = [
            f"   {self.intbin(choosedPacket['IP'].version,4)} . . . . = Version: {choosedPacket['IP'].version}",
            f"   . . . . {self.intbin(choosedPacket['IP'].ihl,4)} = Header Length:  {choosedPacket['IP'].ihl * 4} bytes  ({choosedPacket['IP'].ihl})",
            f"   Differentiated Services Field:   {hex(choosedPacket['IP'].tos)}",
            f"   Total Length:   {choosedPacket['IP'].len}",
            f"   Identification:   {hex(choosedPacket['IP'].id)} ({choosedPacket['IP'].id})",
            f"   Flags:   {flags_detail}",
            f"   Fragment Offset:   {choosedPacket['IP'].frag}",
            f"   Time to Live:   {choosedPacket['IP'].ttl}",
            f"   Protocol:   TCP ({choosedPacket['IP'].proto})",
            f"   Header Checksum:   {checksum_detail}",
            f"   Source:   {choosedPacket['IP'].src}",
            f"   Destination:   {choosedPacket['IP'].dst}"
        ]
        self.current_packet.append(net_packet)

    def choosedIPv6PDUAnalysis(self):
        print("\n\nIPv6协议\n")
        net_packet = {}
        choosedPacket = self.sniffDataList[self.choosePDUNum]
        net_packet["net_type"] = f"Internet Protocol Version 6, Src: {choosedPacket['IPv6'].src}, Dst: {choosedPacket['IPv6'].dst}"
        net_packet["details"] = [
            f"   Version:   {choosedPacket['IPv6'].version}",
            f"   Traffic Class:   {choosedPacket['IPv6'].tc}",
            f"   Flow Label:   {choosedPacket['IPv6'].fl}",
            f"   Payload Length:   {choosedPacket['IPv6'].plen}",
            f"   Next Header:   {choosedPacket['IPv6'].nh}",
            f"   Hop Limit:   {choosedPacket['IPv6'].hlim}",
            f"   Source:   {choosedPacket['IPv6'].src}",
            f"   Destination:   {choosedPacket['IPv6'].dst}",
        ]
        self.current_packet.append(net_packet)

    # 修改 choosedARPPDUAnalysis 方法中的相关内容
    def choosedARPPDUAnalysis(self):
        # 请在此处完成ARP协议的分析器(分析数据包功能)，并添加详细代码注释
        print("\n\nARP协议\n")
        net_packet = {}
        choosedPacket = self.sniffDataList[self.choosePDUNum]
        choosedPacket.show()
        print(choosedPacket['ARP'].op)
        # 根据Opcode确定ARP操作类型
        opcode_str = ""
        if choosedPacket['ARP'].op == 1:
            opcode_str = "request"
        elif choosedPacket['ARP'].op == 2:
            opcode_str = "reply"
        else:
            opcode_str = str(choosedPacket['ARP'].op)
        # 根据硬件类型确定硬件类型描述
        hwtype_str = ""
        if choosedPacket['ARP'].hwtype == 1:
            hwtype_str = "Ethernet"
        else:
            hwtype_str = str(choosedPacket['ARP'].hwtype)
        # 根据协议类型确定协议类型描述
        ptype_str = ""
        if choosedPacket['ARP'].ptype == 0x0800:  # IPv4
            ptype_str = "IPv4"
        elif choosedPacket['ARP'].ptype == 0x0806:  # ARP
            ptype_str = "ARP"
        else:
            ptype_str = str(choosedPacket['ARP'].ptype)
        net_packet["net_type"] = f"Address Resolution Protocol ({opcode_str})"
        net_packet["details"] = [
            f"   Hardware type: {hwtype_str} ({choosedPacket['ARP'].hwtype})",
            f"   Protocol type: {ptype_str} (0x{choosedPacket['ARP'].ptype:04x})",
            f"   Hardware size: {choosedPacket['ARP'].hwlen}",
            f"   Protocol size: {choosedPacket['ARP'].plen}",
            f"   Opcode: {opcode_str} ({choosedPacket['ARP'].op})",
            f"   Sender MAC address: {choosedPacket['ARP'].hwsrc}",
            f"   Sender IP address: {choosedPacket['ARP'].psrc}",
            f"   Target MAC address: {choosedPacket['ARP'].hwdst}",
            f"   Target IP address: {choosedPacket['ARP'].pdst}",
        ]
        self.current_packet.append(net_packet)

    def choosedTCPPDUAnalysis(self):
        # 请在此处完成TCP协议的分析器(分析数据包功能)，并添加详细代码注释
        net_packet = {}
        choosedPacket = self.sniffDataList[self.choosePDUNum]

        # 解析TCP Flags字段
        tcp_flags = choosedPacket['TCP'].flags
        flags_int = int(tcp_flags) if hasattr(tcp_flags, '__int__') else tcp_flags
        flags_binary = format(flags_int, '09b')  # TCP Flags主要为9位
        # 构造详细的Flags输出
        flags_detail = f"0x{flags_int:04x} ({self.tcpflag(flags_int)})\n" \
                       f"        000.  . . . .  . . . .  = Reserved: Not set\n" \
                       f"        . . .{flags_binary[0]}  . . . .  . . . . = Nonce: {'Set' if flags_binary[0] == '1' else 'Not set'}\n" \
                       f"        . . . .  {flags_binary[1]}. . .  . . . . = Congestion Window Reduced (CWR): {'Set' if flags_binary[1] == '1' else 'Not set'}\n" \
                       f"        . . . .  .{flags_binary[2]}. .  . . . . = ECN-Echo: {'Set' if flags_binary[2] == '1' else 'Not set'}\n" \
                       f"        . . . .  . .{flags_binary[3]}.  . . . . = Urgent: {'Set' if flags_binary[3] == '1' else 'Not set'}\n" \
                       f"        . . . .  . . .{flags_binary[4]}  . . . . = Acknowledge: {'Set' if flags_binary[4] == '1' else 'Not set'}\n" \
                       f"        . . . .  . . . .  {flags_binary[5]}. . .  = Push: {'Set' if flags_binary[5] == '1' else 'Not set'}\n" \
                       f"        . . . .  . . . .  .{flags_binary[6]}. .= Reset: {'Set' if flags_binary[6] == '1' else 'Not set'}\n" \
                       f"        . . . .  . . . .  . .{flags_binary[7]} . = Syn: {'Set' if flags_binary[7] == '1' else 'Not set'}\n" \
                       f"        . . . .  . . . .  . . .{flags_binary[8]} = Fin: {'Set' if flags_binary[8] == '1' else 'Not set'}"

        original_checksum = choosedPacket['TCP'].chksum
        # 这里应该添加实际的校验和验证逻辑，但为了简化示例，我们假设校验和是正确的
        # 在实际应用中，您需要根据具体实现来验证校验和
        checksum_status = "Good"  # 可能的值: "Good", "Bad", "Unverified"
        checksum_marker = "[correct]" if checksum_status == "Good" else "[incorrect]" if checksum_status == "Bad" else "[unverified]"
        # 构造校验和的详细输出
        checksum_detail = f"0x{original_checksum:04x} {checksum_marker}\n" \
                          f"      [Checksum Status: {checksum_status}]\n" \
                          f"      [Calculated Checksum: 0x{original_checksum:04x}]"

        net_packet["net_type"] = f"Transmission Control Protocol, Src Port: {choosedPacket['TCP'].sport}, Dst Port: {choosedPacket['TCP'].dport}, ACK: {choosedPacket['TCP'].ack}"
        net_packet["details"] = [
            f"   Source Port:   {choosedPacket['TCP'].sport}",
            f"   Destination Port:   {choosedPacket['TCP'].dport}",
            f"   Sequence number:   {choosedPacket['TCP'].seq}",
            f"   Acknowledge number:   {choosedPacket['TCP'].ack}",
            f"   {self.intbin(choosedPacket['TCP'].dataofs, 4)} . . . . = Header Length:   {choosedPacket['TCP'].dataofs * 4} bytes ({choosedPacket['TCP'].dataofs})",
            f"   Flags:   {flags_detail}",
            f"   Window size value:   {choosedPacket['TCP'].window}",
            f"   Checksum:   {checksum_detail}",
            f"   Urgent pointer:   {choosedPacket['TCP'].urgptr}",
            f"   Options:   {choosedPacket['TCP'].options}"
        ]
        self.current_packet.append(net_packet)

    def choosedUDPPDUAnalysis(self):
        # 请在此处完成UDP协议的分析器(分析数据包功能)，并添加详细代码注释
        print("\n\nUDP协议\n")
        net_packet = {}
        choosedPacket = self.sniffDataList[self.choosePDUNum]
        net_packet["net_type"] = f"User Datagram Protocol, Src Port: {choosedPacket['UDP'].sport}, Dst Port: {choosedPacket['UDP'].dport}"
        net_packet["details"] = [
            f"   Source Port:   {choosedPacket['UDP'].sport}",
            f"   Destination Port:   {choosedPacket['UDP'].dport}",
            f"   Length:   {choosedPacket['UDP'].len}",
            f"   Checksum:   {choosedPacket['UDP'].chksum}",
        ]
        self.current_packet.append(net_packet)

    def IP_headchecksum(self, IP_head):
        checksum = 0
        headlen = len(IP_head)
        if headlen % 2 == 1:
            # b:signed type
            IP_head += b"\0"
        i = 0
        while i < headlen:
            temp = struct.unpack('!H', IP_head[i:i + 2])[0]
            checksum = checksum + temp
            i = i + 2
        # 将高16bit与低16bit相加
        checksum = (checksum >> 16) + (checksum & 0xffff)
        # 将高16bit与低16bit再相加
        checksum = checksum + (checksum >> 16)
        return ~checksum & 0xffff

    #对应进制转换
    def intbin(self, n, count):
        """returns the binary of integer n, using count number of digits"""
        return "".join([str((n >> y) & 1) for y in range(count - 1, -1, -1)])

    def proto_IPcol(self, ori_protocol):
        if ori_protocol == 1:
            proString = 'ICMP'
        elif ori_protocol == 6:
            proString = 'TCP'
        elif ori_protocol == 17:
            proString = 'UDP'
        elif ori_protocol == 89:
            proString = 'OSPF'
        elif ori_protocol == 0:
            proString = 'IPv6 Hop-by-Hop Option'
        elif ori_protocol == 58:
            proString = 'ICMPv6'
        elif ori_protocol == 4:
            proString = 'IP'
        return proString


    def tcpflag(self, tcpflag):  # 将标志位是1的拼接
        flagString = ''
        flag = 0
        if tcpflag & 0x80:
            if flag == 0:
                flagString += 'CWR'
                flag = 1
            else:
                flagString += ', CWR'
        if tcpflag & 0x40:
            if flag == 0:
                flagString += 'ECE'
                flag = 1
            else:
                flagString += ', ECE'
        if tcpflag & 0x20:
            if flag == 0:
                flagString += 'URG'
                flag = 1
            else:
                flagString += ', URG'
        if tcpflag & 0x10:
            if flag == 0:
                flagString += 'ACK'
                flag = 1
            else:
                flagString += ', ACK'
        if tcpflag & 0x08:
            if flag == 0:
                flagString += 'PSH'
                flag = 1
            else:
                flagString += ', PSH'
        if tcpflag & 0x04:
            if flag == 0:
                flagString += 'RST'
                flag = 1
            else:
                flagString += ', RST'
        if tcpflag & 0x02:
            if flag == 0:
                flagString += 'SYN'
                flag = 1
            else:
                flagString += ', SYN'
        if tcpflag & 0x01:
            if flag == 0:
                flagString += 'FIN'
                flag = 1
            else:
                flagString += ', FIN'
        return flagString

    # 十六进制转存
    def generate_hex_dump(self, packet):
        raw_bytes = bytes(packet)
        print("Raw bytes:", raw_bytes)
        print("\n")
        # 按行格式化十六进制数据（类似Wireshark的显示方式）
        for i in range(0, len(raw_bytes), 16):
            # 地址偏移
            line_addr = f"{i:04x}"
            # 十六进制部分
            hex_part = ""
            # ASCII部分
            ascii_part = ""
            # 处理每行16个字节
            for j in range(16):
                if i + j < len(raw_bytes):
                    byte_val = raw_bytes[i + j]
                    hex_part += f"{byte_val:02x} "
                    # 可打印字符显示原字符，否则显示点号
                    if 32 <= byte_val <= 126:
                        ascii_part += chr(byte_val)
                    else:
                        ascii_part += "."
                else:
                    hex_part += "   "  # 填充空格
            # 格式化一行十六进制转储
            self.hexadecimal_dump.append([line_addr, hex_part, ascii_part])

        print(self.hexadecimal_dump)

